package com.demo.jwt.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.demo.jwt.annotation.PassToken;
import com.demo.jwt.annotation.LoginRequired;
import com.demo.jwt.dao.UserDao;
import com.demo.jwt.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    UserDao userDao;

//    @Value("${admins.user}")
//    private String user;
//
//    @Value("${admins.password}")
//    private String password;

    /**
     * 从http请求头中取出token
     * 判断是否映射到方法
     * 检查是否有passToken注解，有则跳过验证
     * 建厂用没有用户登录的注解， 有则需要取出并验证
     * 认证通过则可以访问， 不过则报错
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查是否有passToken注解，有则跳过验证
        if (method.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        // 检查是否需要用户权限的注解
        if (method.isAnnotationPresent(LoginRequired.class)) {
            // 有进行验证
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            if (loginRequired != null) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token,请重新登陆");
                }
                // 获取token中的username
                String username;
                try {
                    username = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
//                if (user.equals(username)) {
//                    throw new RuntimeException("用户名错误");
//                }
                 User user = userDao.findByUsername(username);
                 if (user == null) {
                    throw new RuntimeException("用户不存在");
                 }
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                 try {
                     jwtVerifier.verify(token);
                 } catch (JWTVerificationException j) {
                     throw new RuntimeException("401");
                 }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
